import os
import subprocess

from flask import redirect, url_for


def write_code(path, codes):
    with open(path, 'w',encoding='utf-8') as f:
        f.write(codes)
        f.close()


def get_input(input_path):
    answers = []
    f = open(input_path, 'r')
    file_content = f.read()
    multiline_list = file_content.split("\n---\n")

    # 去掉每个多行文本末尾的换行符
    multiline_list = [item.strip() for item in multiline_list]
    multiline_list = multiline_list[0:len(multiline_list)-1]
    # while line:
    #     answers.append(str(line))
    #     line = f.readline()
    return multiline_list


def get_output(output_path):
    f = open(output_path, 'r')
    file_content = f.read()
    multiline_list = file_content.split("\n---\n")

    # 去掉每个多行文本末尾的换行符
    multiline_list = [item.strip() for item in multiline_list]
    multiline_list = multiline_list[0:len(multiline_list)-1]
    # while line:
    #     answers.append(str(line))
    #     line = f.readline()
    return multiline_list


def is_right(path, class_id, ID):
    # 在命令行运行程序ID)
    print("开始检测")
    basepath = 'code/'
    class1 = "class" + str(class_id)
    # Windows系统使用.exe，Linux使用.out
    if os.name == 'nt':  # Windows
        filename = str(ID) + ".exe"
    else:  # Linux/Unix
        filename = str(ID) + ".out"
    path1 = basepath + class1 + "/" + filename
    if class1 not in os.listdir(basepath):
        os.mkdir(basepath + class1)
    # "gcc homework_uploads/3-求1+2+3/class1\201892418.c -o code/class1/201892418.out && cd code/class1 && 201892418.out"
    # 'gcc ' + path + ' -o ' + path1
    cmd_order = []
    cmd_order.append("gcc")
    cmd_order.append(path)
    cmd_order.append("-o")
    cmd_order.append(path1)
    cmd_order.append("-lm")
    print(cmd_order)
    print("当前目录是：1")
    print(os.path.dirname(os.path.abspath(__file__)))
    proc = subprocess.Popen(cmd_order, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                            stdin=subprocess.PIPE)
    print(proc.stdout.readline())
    proc.stdin.flush()
    proc.stdin.close()
    # # 打印输出结果
    err = proc.stderr.read().decode()
    out = proc.stdout.readline()
    print("Standard Error:")
    print(err)
    print("Standard Out:")
    print(out)
    a = int(len(err))
    # 判断是否编译错误
    result = [True, ""]
    if not a == 0:
        errs = err.split(path)
        print(errs)
        i = 1
        err_out = ""
        while i < len(errs):
            err_out = err_out + errs[i]
            i = i + 1
        result = [False, err_out]
    return result
